import {PageHeaderWrapper} from '@ant-design/pro-layout';
import React from 'react';
import {Card, Col, Row, Skeleton, Spin} from 'antd';
import styles from './index.less';
import {connect} from "dva";
import {trigger} from "@/utils/utils";
import {dateFormat,convertDateFromString, currentTime} from "@/utils/time";
import echarts from 'echarts'
import 'echarts/lib/chart/bar';
// 引入提示框和标题组件
import 'echarts/lib/component/tooltip';
import 'echarts/lib/component/title';
import Pie from '@/pages/GaoLu/components/Pie'
import {DatePicker} from 'antd'
import moment from "moment";

const {RangePicker} = DatePicker;

class ItemDetail extends React.Component {

  extra = {count: 1};

  chart = null;


  charts = {};

  state = {
    display: [],
    autoScore: {
      curScore: null,
      lastHourScore: null
    },
    // status: {1: '低', 2: '正常', 3: '正常', 4: '正常', 5: '高'},
    isShow: false,
    // 默认一小时间隔
    startTime: convertDateFromString(localStorage.getItem("scoreQuntileStart")),
    endTime: convertDateFromString(localStorage.getItem("scoreQuntileEnd"))
  };


  static getDerivedStateFromProps(nextProps, prevState) {
    const {autoScore} = nextProps;
    // 及时更新display
    if (autoScore && autoScore !== prevState.autoScore) {
      const display = [];
      if (!autoScore.valueDict) return null;
      for (const [key, value] of Object.entries(autoScore.valueDict)) {
        display.push({
          key,
          desc: value,
          // status: prevState.status[value],
          status: autoScore.status[key + "_status"],
          data: autoScore.value[key]
        })
      }
      return {
        display,
        autoScore
      }
    }
    return null;
  }

  componentDidMount() {
    // this.scoreQuntileReq = requestAnimationFrame(() => dispatch({type: 'gaolu/getScoreQuntile'}));
  }

  componentDidUpdate() {
    const {autoScore, scoreQuntile,quntileEffect} = this.props;
    const {display} = this.state;

    if (autoScore && scoreQuntile) {
      for (const i of display) {
        const {key} = i;
        this.initChart(key, scoreQuntile[key], autoScore.value[key],quntileEffect)
      }
    }

  }

  componentWillUnmount() {
    Object.values(this.charts).map(chart => chart.dispose());
    // cancelAnimationFrame(this.scoreQuntileReq);
  }

  initChart = (key, value, current,quntileEffect=false) => {
    let chart = this.charts[key];
    if (chart == null) {
      const dom = document.getElementById(`s-${key}`);
      chart = echarts.init(dom);
      chart.showLoading({
        text: '数据正在加载...',
        textStyle: { fontSize : 30 , color: '#444' },
        effectOption: {backgroundColor: 'rgba(0, 0, 0, 0)'}
      });
    }

    if (quntileEffect) {
      chart.showLoading({
        text: '数据正在加载...',
        textStyle: { fontSize : 30 , color: '#444' },
        effectOption: {backgroundColor: 'rgba(0, 0, 0, 0)'}
      });
    }

    const newArray = [];
    let max = 0;
    for (let i = 0; i < value[0].length; i++) {
      newArray.push([value[0][i], value[1][i]]);
      if (value[1][i] > max) {
        max = value[1][i]
      }
    }

    const option = {
      tooltip: {
        show: true,
        trigger: 'item'
      },
      backgroundColor: '#fff',
      grid: {
        top: '15%',
        bottom: '20%'
      },
      xAxis: {
        type: 'value',
        splitLine: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        splitLine: {
          show: false
        },
        axisLabel: {
          formatter: '{value}%'
        }
      },
      series: [{
        type: 'bar',
        barWidth: 11, // 固定柱子宽度
        data: newArray

      },
        {
          data: newArray,
          type: 'line',
          smooth: true // 让曲线变平滑
        }]
    };
    option.series[0].markLine = {
      symbol: "none",
      lineStyle: {               // 警戒线的样式  ，虚实  颜色
        type: "solid",
        color: "#000",
      },
      label: {
        position: 'end',
        formatter: `${current}`
      },
      data: [
        //配置线端起始点
        [
          {
            coord: [current, 0]
          },
          {
            coord: [current, max]
          }
        ]
      ]
    };
    chart.setOption(option,true);
    if (!quntileEffect) {
      chart.hideLoading()
    }
    this.charts[key] = chart
  };


  getAutoScore = () => {
    this.props.dispatch({
      type: 'gaolu/autoScore',
      payload: {
        end: dateFormat(this.state.endTime),
      }
    });
  };

  getScoreQuntile = (ifFresh = false) => {
    const {startTime,endTime} = this.state;
    this.props.dispatch({
      type: 'gaolu/getScoreQuntile',
      payload: {
        start:dateFormat(startTime),
        end:dateFormat(endTime),
        refresh: ifFresh
      }
    });
  };

  timePick = value => {
    this.state.startTime = value[0].toDate();
    this.state.endTime = value[1].toDate();
    localStorage.setItem("scoreQuntileStart",dateFormat(this.state.startTime));
    localStorage.setItem("scoreQuntileEnd",dateFormat(this.state.endTime));

    this.getScoreQuntile(true);
  };

  render() {
    const format = 'YYYY-MM-DD';
    const {autoScore, display, endTime, startTime} = this.state;
    const {quntileEffect} = this.props;

    const value = endTime !== null && startTime !== null?
      [moment(startTime, format), moment(endTime, format)] : undefined;

    const DOM = display.map(item =>
      (
        <Col span={8} key={item.key}>
          <Row className={styles.scoreChart}>
            <Col span={5}>
              <h4 className={styles.chartTitle}>{item.desc}</h4>
              <h4 className={styles.chartBody}>{item.data ? item.data.toFixed(2) : 0}</h4>
              <h4 className={styles.chartStatus}>{item.status}</h4>
            </Col>
            <Col span={19}>
              <div id={`s-${item.key}`} style={{height: 140}}/>
            </Col>
          </Row>
        </Col>));


    return (
      <div>
        <Row style={{display: 'flex', marginBottom: 10}}>
          <RangePicker
            format={format}
            placeholder={['开始时间', '结束时间']}
            onChange={this.timePick}
            style={{width: 300}}
            defaultValue={value}
          />
        </Row>

        {/*{quntileEffect && <p style={{marginTop: 20}}>加载历史数据中..</p>}*/}

        { display.length > 0 && <Row>
          <Col span={4}>
            <Pie name='当前' chartId='pieOfPass' data={autoScore.curScore}/>
          </Col>
          <Col span={4}>
            <Pie name='上一小时' chartId='pieOfCur' data={autoScore.lastHourScore}/>
          </Col>
          {DOM}
        </Row>
        }
        {display.length === 0 && <p style={{marginTop: 20}}>当前暂无详情</p>}
      </div>
    );
  }
}

export default connect(({gaolu, loading}) => ({
  autoScore: gaolu.autoScore,
  scoreQuntile: gaolu.scoreQuntile,
  quntileEffect: loading.effects['gaolu/getScoreQuntile'],
}))
(ItemDetail);
